package repository

import (
	"context"
	"go-admin-server/app/dao"
	"go-admin-server/app/dao/model"
	"go-admin-server/common/errors"
)

var UserRepo = new(userRepo)

type userRepo struct{}

func (a *userRepo) GetUserByName(name string) (*model.User, error) {
	user := new(model.User)
	if err := dao.DB.Where("user_name = ?", name).First(&user).Error; err != nil {
		return nil, err
	}
	return user, nil
}

func (a *userRepo) Delete(ctx context.Context, id uint64) error {
	result := dao.DB.Debug().Where("id=?", id).Delete(model.User{})
	return errors.WithStack(result.Error)
}

func (a *userRepo) SelectById(id uint64) (user *model.User, err error) {
	err = dao.DB.Debug().Where("id=?", id).First(&user).Error
	return user, err
}

func (a *userRepo) UpdatePassword(id uint64, password string) error {
	return dao.DB.Where("id=?", id).Update("password", password).Error
}

func (a *userRepo) Create(user *model.User) error {
	return dao.DB.Create(&user).Error
}

func (a *userRepo) Update(id uint64, user *model.User) error {
	return dao.DB.Where("id=?", id).Updates(&user).Error
}

func (a *userRepo) UpdateStatus(id uint64, status int) error {
	return dao.DB.Where("id=?", id).Update("status", status).Error
}

func (a *userRepo) Migrate() error {
	return dao.DB.AutoMigrate(&model.User{})
}
